package com.dongan.service.security;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.dongan.mapper.PermissionMapper;
import com.dongan.mapper.UsersMapper;
import com.dongan.pojo.SecurityUser;
import com.dongan.pojo.UserLogin;
import com.dongan.pojo.Users;
import com.dongan.utils.CommonProp;
import com.dongan.utils.SerialNumber;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * @ClassName:UserSerivce
 * @Description:
 * @Author:longtao
 * @Date:2021/6/28
 * @Version:1.0
 */
@Service(value = "userDetailsService")
public class UserServiceImpl implements UserDetailsService {
    @Autowired
    private UsersMapper usersMapper;

    @Autowired
    private PermissionMapper permissionMapper;
    @Autowired
    private SecurityUser user;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        QueryWrapper<Users> usersQueryWrapper = new QueryWrapper<>();
        usersQueryWrapper.eq("email", username);
        Users users = usersMapper.selectOne(usersQueryWrapper);
        if (users == null) {
            throw new UsernameNotFoundException("用户找不到!");
        }
        UserLogin curUser = new UserLogin();
        BeanUtils.copyProperties(users, curUser);
        //根据用户信息查询出权限列表
        List<String> strings = permissionMapper.queryPermissionList(users.getId());
        //查询出的权限,可能会重复,所以我们需要使用set来去除重复的元素
        Set<String> stringSet = new HashSet<>(strings);
        List<String> list = new ArrayList<>(stringSet);
        CommonProp.userLogin = curUser;
        CommonProp.permission = list;

        Users users1 = new Users();
        QueryWrapper<Users> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("email", username);
        Users one = usersMapper.selectOne(queryWrapper);
        CommonProp.user=one;
        SerialNumber.user=one;
        user.setUserInfo(curUser);
        user.setPermissionValueList(list);
        return user;
    }
}
